<?php
namespace control;
/*
*材料分配记录类
*/

class materialDistributeRecordClass extends adIndexClass
{
    private const page = 'materialDistributeRecord';
    private const table = 'material_distribute';//成本分摊主表
    private const table_num = 'material_distribute_num';//数量分配表
    private const table_source = 'material_distribute_source';//源单表
    private const table_detail = 'material_distribute_detail';//库存分配表
    private const title = '材料分配记录';

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'orderType'          => [
                        'name'  => "单据类型",
                        'width' => 100,
                    ],
                    'orderNo'  => [
                        'name'  => '单据编号',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'type'         => [
                        'name'  => '加工单类型',
                        'width' => 100,
                    ],
                    'line'          => [
                        'name'  => '生产线',
                        'width' => 200,
                    ],
                    'subject'          => [
                        'name'  => '存货类别',
                        'width' => 100,
                    ],
                    'code'          => [
                        'name'  => '物料编码',
                        'width' => 150,
                    ],
                    'name'          => [
                        'name'  => '物料名称',
                        'width' => 150,
                    ],
                    'model'          => [
                        'name'  => '规格型号',
                        'width' => 100,
                    ],
                    'unit'          => [
                        'name'  => '单位',
                        'width' => 60,
                    ],
                    'num'          => [
                        'name'  => '生产数量',
                        'width' => 100,
                    ],
                    'passNum'          => [
                        'name'  => '合格数量',
                        'width' => 100,
                    ],
                    'scrapNum'          => [
                        'name'  => '报废数量',
                        'width' => 100,
                    ],
                    'startDate'          => [
                        'name'  => '计划开工时间',
                        'width' => 120,
                        'sort' => 1,
                    ],
                    'endDate'          => [
                        'name'  => '计划完工时间',
                        'width' => 120,
                        'sort' => 1,
                    ],
                    'recordDate'          => [
                        'name'  => '单据日期',
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'state'          => [
                        'name'  => '状态',
                        'width' => 100,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "单据编号" => text(array("name" => "orderNo")),
                    "单据日期" => text(array("name" => "createTime", 'laydate' => ['type' => 'date', 'range' => '~'])),
                    "状态" => select(["name" => "state", 'option' => ['草稿', '待确认', '已确认']]),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*列表-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        $button = "";
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {
        //like查询数组
        $like = array(
            "c.orderNo" => $this->post('orderNo'),
        );
        //全等查询数组
        $equal = array(
            "a.state" => $this->post('state'),
            'a.coid' => self::$coid,
        );
        $and = '';
        if ($this->post('createTime')) {
            $and .= self::timeComparison($this->post('createTime'), 'date', 'c.recordDate');
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'c.recordDate desc,c.orderNo',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array(
            "table" => self::table." as a join ".self::table_source.' as b on a.id = b.orderId join machining_order as c on b.machiningOrderId = c.id',
            "where" => $where,
            'field'=>"b.*,c.orderType,c.orderNo,a.lineId,c.recordDate,c.type,c.startDate,c.endDate,a.state",
            "order" => $orderBy['orderBy']
        ));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        $url = root . "control/adIndex.html?cla=" . self::page;
        $costAllocation = new costAllocationClass();
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
                "edit" => array("title" => "编辑", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=edit&id=" . $array['orderId'] . "')"),
                "detail" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=detail&id=" . $array['orderId'] . "')"),
            );
            if ($array['state'] == '已确认') {
                unset($dominate['edit']);
            }
            $machiningOrderMx = query('machining_order_mx',"id = '$array[machiningOrderMxId]'");
            $material = query('material', "id = '$machiningOrderMx[materialId]'");
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'line':
                        $line = query('product_line', "id = '$array[lineId]'");
                        $row[] = $line['workshop'].'-'.$line['name'];
                        break;
                    case 'num':
                        $row[] = self::lostZero($machiningOrderMx['num'],'numPrecision');
                        break;
                    case 'passNum':
                        $passNum = $costAllocation->getMaterialNum($machiningOrderMx['id'], $machiningOrderMx['unit']);
                        $row[] = $passNum;
                        break;
                    case 'scrapNum':
                        $scrapNum = $costAllocation->getMaterialNum($machiningOrderMx['id'], $machiningOrderMx['unit'], '报废');
                        $row[] = $scrapNum;
                        break;
                    case 'subject':
                    case 'code':
                    case 'name':
                    case 'model':
                        $row[] = $material[$key];
                        break;
                    case 'unit':
                        $row[] = $machiningOrderMx['unit'];
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        $totalQuery = find([
            'table'  => 'machining_order_mx',
            'single' => " id in (select b.machiningOrderMxId from ".self::table." as a join ".self::table_source." as b on a.id = b.orderId join machining_order as c on b.machiningOrderId = c.id where 1=1 {$where}) ",
            'field'  => "ifnull(sum(num),0) as num",
        ]);
        $passQuery = find(array(
            'table'  => "machining_order_mx as mom join material as mat on mom.materialId = mat.id join machining_in_order_detail as miod on miod.sourceId = mom.id join inventory_detail as mx on mx.sourceId = miod.id ",
            'single'=>" mom.id in (select b.machiningOrderMxId from ".self::table." as a join ".self::table_source." as b on a.id = b.orderId join machining_order as c on b.machiningOrderId = c.id where 1=1 {$where}) ",
            'field'=>"ifnull(SUM((CASE WHEN mx.unit = mat.unit_one THEN mx.num*mat.unit_one_num WHEN mx.unit = mat.unit_two THEN mx.num*mat.unit_two_num ELSE mx.num END)/(CASE WHEN mom.unit = mat.unit_one THEN mat.unit_one_num WHEN mom.unit = mat.unit_two THEN mat.unit_two_num ELSE 1 END)),0) AS num"
        ));
        $scrapQuery = find(array(
            'table'  => "machining_order_mx as mom join material as mat on mom.materialId = mat.id join machining_in_order_detail as miod on miod.sourceId = mom.id join quality_order as mx on mx.sourceMxId = miod.id ",
            'single'=>" mom.id in (select b.machiningOrderMxId from ".self::table." as a join ".self::table_source." as b on a.id = b.orderId join machining_order as c on b.machiningOrderId = c.id where 1=1 {$where}) and mx.type = 2 and mx.coid = '" . self::$coid . "' and mx.state = '已质检' ",
            'field'=>"ifnull(SUM((CASE WHEN mx.unit = mat.unit_one THEN (mx.num-mx.passNum)*mat.unit_one_num WHEN mx.unit = mat.unit_two THEN (mx.num-mx.passNum)*mat.unit_two_num ELSE (mx.num-mx.passNum) END)/(CASE WHEN mom.unit = mat.unit_one THEN mat.unit_one_num WHEN mom.unit = mat.unit_two THEN mat.unit_two_num ELSE 1 END)),0) AS num"
        ));
        $total    = [
            'num'        => self::lostZero($totalQuery['num'], 'numPrecision'),
            'passNum'        => self::lostZero($passQuery['num'], 'numPrecision'),
            'scrapNum'        => self::lostZero($scrapQuery['num'], 'numPrecision'),
        ];
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
            "total"       => $total,
        ));
        //返回
        $json['html'] = $page['hint'] . "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }
    /**
     * 保存并提交
     * @return bool|string
     */
    public function saveAndCommit(): bool|string
    {
        $resultJson = $this->editEdit();
        $result = json_decode($resultJson,true);
        if ($result['warn'] == 2){
            unset($_SESSION['warn']);
            $resultJson = $this->commitEdit();
        }
        return $resultJson;
    }
    /**
     * 编辑页
     * @return string
     */
    public function edit(): string
    {
        $id = $this->get('id')?:suiji();
        $costAllocation = new costAllocationClass();
        $info = query(self::table,"id = '$id'");
        $machiningOrderClass = new machiningOrderClass();
        $button[] = [
            'style' => 'li-btn-blue-bg',
            "name" => "保存",
            "type" => "点击事件",
            "title" => "保存",
            'fun' => "subForm('materialDistributeRecordEditForm','" . root . "control/adIndex.html?cla=" . self::page . "&fun=editEdit')"
        ];
        $button[] = [
            "name" => "保存并提交",
            "type" => "点击事件",
            "title" => "保存",
            'fun' => "subForm('" . self::page . "EditForm','" . root . "control/adIndex.html?cla=" . self::page . "&fun=saveAndCommit')"
        ];
        $line = query('product_line', "id = '$info[lineId]'");


        $material_list = [];
        $bomAll = [];
        $all = find(array('table' => 'machining_order_mx', "where" => "coid = '" . self::$coid . "' and id in (select machiningOrderMxId from material_distribute_source where orderId = '$id') order by list asc"));
        foreach ($all['array'] as $array) {
            $machining_order = query('machining_order',"id = '$array[orderId]'");
            $result_list = machiningOrderClass::singleBomMx($array['bomId'], $array['materialId'], $array['num'], $array['unit']);
            $material_list = $machiningOrderClass->merge_material_two($material_list, $result_list);
            $bomArray = $machiningOrderClass->getFactMaterialNum($machining_order['id']);
            $bomAll = $machiningOrderClass->mergeBomArray($bomAll,$bomArray);
        }
        $bomAll = $machiningOrderClass->singleBomArray($bomAll);

        //线边库存
        $tr[] = ['', '生产线', '存货类别', '物料编码', '物料名称', '规格型号', '单位', '库存数量', '实际BOM用量', '本次分配'];
        $all = find(array('table'=>self::table_detail,'where'=>"orderId = '$id' order by list"));
        $totalArr = ['bom_num'=>0,'dis_num'=>0];
        foreach ($all['array'] as $k=>$array){
            $material = query('material', "id = '$array[materialId]'");
            $stockNum = tempInventoryClass::inventoryNum($array['materialId'], $material['unit'], $line['id']);
            $totalArr['bom_num'] +=  isset($bomAll[$array['materialId']])&&$bomAll[$array['materialId']]?$bomAll[$array['materialId']]:0;
            $totalArr['dis_num'] += $array['num'];
            $bomNum = isset($bomAll[$array['materialId']])&&$bomAll[$array['materialId']]?self::lostZero($bomAll[$array['materialId']],'numPrecision'):0;
            $tr[] =[
                componentClass::tablePperation($k+1,'delTableRow(this);calculateInventoryTotal($("#materialTable"))').
                hidden(array('name' => 'detailId[]', 'value' => $array['id'])) .
                hidden(array('name' => 'materialId[]', 'value' => $array['materialId'])),
                $line['workshop'].'-'.$line['name'],
                $material['subject'],
                $material['code'],
                $material['name'],
                $material['model'],
                $material['unit'],
                $stockNum,
                "<span class='bom_num'>{$bomNum}</span>",
                text(array('name'=>'num[]','value'=>self::lostZero($array['num'],'numPrecision'), 'other' => self::digitalFiltering('numPrecision')." onblur=\"calculateInventoryTotal($('#materialTable'))\" "))
            ];
        }
        $total      = [
            8  => "<span id='bom_num'>".self::formattingFigure($totalArr['bom_num'],'num')."</span>",
            9  => "<span id='dis_num'>".self::formattingFigure($totalArr['dis_num'],'num')."</span>",
        ];
        $list = $this->listTable(array('tr' => $tr, 'end' => true, 'total' => $total));


        //源单
        $sourceTr[] = ['操作', '单据日期', '单据编号', '加工类型', '生产线', '存货类别', '物料编码', '物料名称', '规格型号', '单位', '计划数量', '合格数量', '报废数量', 'BOM版本'];
        $all = find(array('table'=>self::table_source,'where'=>"orderId = '$id' order by list"));
        $totalArr = ['plan_num'=>0,'pass_num'=>0,'scrap_num'=>0];
        foreach ($all['array'] as $k=>$array){
            $machining_order_mx = query('machining_order_mx', "id = '$array[machiningOrderMxId]'");
            $machining_order = query('machining_order', "id = '$machining_order_mx[orderId]'");
            $type = $machining_order['orderType'] == '生产计划' ? '生产计划单' : '半成品加工单';
            $material = query('material', "id = '$machining_order_mx[materialId]'");
            $bom = query('bom', "id = '$machining_order_mx[bomId]'");
            $passNum = $costAllocation->getMaterialNum($machining_order_mx['id'], $machining_order_mx['unit']);
            $scrapNum = $costAllocation->getMaterialNum($machining_order_mx['id'], $machining_order_mx['unit'], '报废');
            $sourceTr[] = [
                componentClass::tablePperation($k+1,"delTableRow(this);calculateTotal()").
                hidden(array('name' => 'mxId[]', 'value' => $array['id'])) .
                hidden(array('name' => 'sourceId[]', 'value' => $array['machiningOrderMxId'])),
                $machining_order['recordDate'],
                $machining_order['orderNo'],
                $type,
                $line['workshop'] . '-' . $line['name'],
                $material['subject'],
                $material['code'],
                $material['name'],
                $material['model'],
                $machining_order_mx['unit'],
                "<span class='plan_num'>".self::lostZero($machining_order_mx['num'],'numPrecision')."</span>",
                "<span class='pass_num'>".$passNum."</span>",
                "<span class='scrap_num'>".$scrapNum."</span>",
                $bom['bomVersion']
            ];
            $totalArr['plan_num'] += $machining_order_mx['num'];
            $totalArr['pass_num'] += $passNum;
            $totalArr['scrap_num'] += $scrapNum;
        }
        $total      = [
            10  => "<span id='plan_num'>".self::formattingFigure($totalArr['plan_num'],'num')."</span>",
            11  => "<span id='pass_num'>".self::formattingFigure($totalArr['pass_num'],'num')."</span>",
            12  => "<span id='scrap_num'>".self::formattingFigure($totalArr['scrap_num'],'num')."</span>",
        ];
        $sourceList = $this->listTable(array('tr' => $sourceTr, 'end' => true, 'total' => $total));

        //源单
        $tableBut = <<<efo
                <span class="smallButton" onclick="chooseSourceOrder()">关联源单</span>
                <span class="smallButton" onclick="bom()">计算BOM</span>
efo;
        //线边库存选择
        $table2But = <<<efo
                <span class="smallButton" onclick="chooseInventory()">线边库存选择</span>
efo;
        $materialDis = new materialDistributeClass();
        //表单
        $data['button'] = $this->tableShowButton($button);
        $body = $this->edit4([
            '基本信息' => [
                [
                    must . "生产线：" => repeatSelect(array(
                            'name' => 'workshop',
                            'value'=>$line['workshop'],
                            'title' => '生产车间',
                            'change' => "getLine",
                            'sqlForm' => "product_line where coid = '" . self::$coid . "' and state = '启用'",
                            'sqlField' => 'workshop'
                        )) .
                        idSelect(array(
                            'name' => 'lineId',
                            'value'=>$line['id'],
                            'sqlForm' => "product_line where coid = '" . self::$coid . "' and state = '启用' and workshop = '$line[workshop]'",
                            'sqlId' => 'id',
                            'sqlField' => 'name',
                            'title' => '生产线'
                        )),
                    must . "单据日期：" => text(["name" => "recordDate", 'laydate' => [], "value" => $info['recordDate']?:$this->date]),
                    must . "分配方式：" => radio(array('name' => 'type', 'value' => $materialDis->typeOption, 'checked' => $info['type']?:1)),
                ],
            ]
        ]);
        $body .= $this->editList([
            'id' => 'orderTable',
            'title' => '源单据',
            'button' => $tableBut,
            'html' => $sourceList,
        ]);
        $body .= $this->editList([
            'id' => 'materialTable',
            'title' => '分配材料',
            'button' => $table2But,
            'html' => $list,
        ]);
        $data['html'] = $this->pageEdit([
            "html" => $body,
            'hidden' => hidden(['name' => 'id', 'value' => $id]),
        ]);
        $data['html'] .= $this->editJs();
        //返回
        return $this->tab($data);
    }

    private function editJs()
    {
        $cla = 'materialDistribute';
        return <<<eof
<script>
function bom(){
    $.post(root+'control/adIndex.html?cla=$cla&fun=bom',$('form[name=materialDistributeRecordEditForm]').serialize(),function(res) {
      if (res.warn==2){
            $("#materialTable tbody").empty().append(res.html);
      }else{
          msg(res.warn,'error')
      }
    },'json')
}
function chooseInventory(){
     let lineId = $("[name='lineId']").val();
    if (!lineId){
        msg('请先选择生产线','error')
    }else{
        layer('$cla','addStock',$('form[name=materialDistributeRecordEditForm]').serialize())
    }
    
}
function chooseSourceOrder(){
    let lineId = $("[name='lineId']").val();
    if (!lineId){
        msg('请先选择生产线','error')
    }else{
        layer('$cla','addOrder',$('form[name=materialDistributeRecordEditForm]').serialize())
    }
}
//获取生产线
function getLine(e){
     let val = e.value;
     $.post(root+'control/adIndex.html?cla=machiningOrder&fun=getLine',{val:val},function(res) {
             $("select[name='lineId']").html(res.html);
        },'json');
}
function addOrder(){
     $.post(root+'control/adIndex.html?cla=$cla&fun=addOrderEdit',$("form[name='orderForm']").serialize(),function (res){
           $("#orderTable tbody").append(res.html);
           resetNumber($("#orderTable"))
           calculateTotal()
         },'json');
}
//计算计划数量
function calculateTotal(table=''){
    table = table ? table : $('.editList')
    let plan_num = 0,
    pass_num = 0,
    scrap_num = 0
    table.find(".plan_num").each(function(index){
        if($(this).text()){
          plan_num+=Number($(this).text());
        }
        var passNumText = table.find(".pass_num").eq(index).text()
        if(passNumText){
            pass_num+=Number(passNumText);
        }
        var scrapNumText = table.find(".scrap_num").eq(index).text()
        if(scrapNumText){
            scrap_num+=Number(scrapNumText);
        }
    })
    $("#plan_num").text(plan_num.toFixed(publicSettings.numPrecision.num));
    $("#pass_num").text(pass_num.toFixed(publicSettings.numPrecision.num));
    $("#scrap_num").text(scrap_num.toFixed(publicSettings.numPrecision.num));
}
function addStock(){
     $.post(root+'control/adIndex.html?cla=$cla&fun=addStockEdit',$("form[name='stockForm']").serialize(),function (res){
           $("#materialTable tbody").append(res.html);
           resetNumber($("#materialTable"))
           calculateInventoryTotal($('#materialTable'))
         },'json');
}
//计算计划数量
function calculateInventoryTotal(table=''){
    table = table ? table : $('.editList')
    let bom_num = 0,
    dis_num = 0
    table.find("[name='num[]']").each(function(index){
        if($(this).val()){
          dis_num+=Number($(this).val());
        }
        var bomNumText = table.find(".bom_num").eq(index).text()
        if(bomNumText){
            bom_num+=Number(bomNumText);
        }
    })
    $("#bom_num").text(bom_num.toFixed(publicSettings.numPrecision.num));
    $("#dis_num").text(dis_num.toFixed(amountPrecision));
}
</script>
eof;

    }


    public function editEdit()
    {
        $id = $this->post('id') ?: self::getId();
        //源单
        $mxIdArr = $this->post('mxId') ?: [];
        $sourceIdArr = $this->post('sourceId');

        //分配材料
        $detailIdIdArr = $this->post('detailId') ?: [];
        $numArr = $this->post('num');
        $materialIdArr = $this->post('materialId');

        $field = [
            'lineId' => $this->post('lineId'),
            'type' => $this->post('type'),
            'recordDate' => $this->post('recordDate'),
        ];
        $annotation = [
            'lineId' => '生产线',
            'type' => '分配方式',
            'recordDate' => '单据日期',
        ];
        $rules = [
            'lineId' => 'required',
            'type' => 'required',
            'recordDate' => 'required',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }
        $where = " id = '$id' ";
        $info = query(self::table, $where);
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有编辑" . self::title . "的权限";
        } elseif (static::is_null_array($mxIdArr)) {
            $json['warn'] = '请选择源单';
        } elseif (static::is_null_array($sourceIdArr)) {
            $json['warn'] = '请选择源单';
        } elseif (static::is_null_array($detailIdIdArr)) {
            $json['warn'] = '请选择需要分配的材料';
        } elseif (static::is_null_array($materialIdArr)) {
            $json['warn'] = '请选择需要分配的材料';
        } elseif (static::is_null_array($numArr)) {
            $json['warn'] = '请填写数量';
        } else {
            $this->startTrans();
            if (!$info['id']) {
                $userNo = codeTemplateClass::generateCode(self::page,[
                    'prefix' => 'CLFP' . date('Ymd', strtotime($field['recordDate'])),
                    'table' => self::table,
                    'field' => 'orderNo',
                    'where' => '',
                ],$field);
                $field = array_merge($field, [
                    'id' => $id,
                    'orderNo' => $userNo,
                    'state' => '草稿',
                    'coid' => self::$coid,
                    'stid' => $this->control['stid'],
                ]);
                $json['warn'] = static::insert(["table" => self::table, "field" => $field]);
            } else {
                $json['warn'] = static::update([
                    "table" => self::table,
                    "field" => $field,
                    "where" => $where
                ]);
            }

            //源单
            foreach ($mxIdArr as $k => $nid) {
                $mx = query(self::table_source, "id = '$nid'");
                $machiningOrderMx = query('machining_order_mx', "id = '$sourceIdArr[$k]'");
                $machiningOrder = query('machining_order', "id = '$machiningOrderMx[orderId]'");
                if (!empty($mx['id'])) {
                    //更新
                    $warn = static::update([
                        "table" => self::table_source,
                        "field" => [
                            'machiningOrderMxId' => $sourceIdArr[$k],
                            'machiningOrderId' => $machiningOrder['id'],
                            'sourceType' => $machiningOrder['orderType'],
                        ],
                        "where" => " id = '$nid'"
                    ]);
                } else {
                    //新增
                    $warn = static::insert([
                        "table" => self::table_source,
                        "field" => [
                            'id' => $nid,
                            'orderId' => $id,
                            'coid' => self::$coid,
                            'machiningOrderMxId' => $sourceIdArr[$k],
                            'machiningOrderId' => $machiningOrder['id'],
                            'sourceType' => $machiningOrder['orderType'],
                        ],
                    ]);
                }
                if (!in_array($warn, ['新增成功', '更新成功'])) {
                    $json['warn'] = $warn;
                    break;
                }
            }

            foreach ($detailIdIdArr as $k => $mxId) {
                $mx = query(self::table_detail, "id = '$mxId'");
                $material = query('material', "id = '$materialIdArr[$k]'");
                $numArr[$k] = self::formattingFigure($numArr[$k],'numPrecision');
                if (!empty($mx['id'])) {
                    //更新
                    $warn = static::update([
                        "table" => self::table_detail,
                        "field" => [
                            'materialId' => $material['id'],
                            'unit' => $material['unit'],
                            'num' => $numArr[$k],
                        ],
                        "where" => " id = '$mxId'"
                    ]);
                } else {
                    //新增
                    $warn = static::insert([
                        "table" => self::table_detail,
                        "field" => [
                            'id' => $mxId,
                            'orderId' => $id,
                            'coid' => self::$coid,
                            'materialId' => $material['id'],
                            'unit' => $material['unit'],
                            'num' => $numArr[$k],
                        ],
                    ]);
                }
                if (!in_array($warn, ['新增成功', '更新成功'])) {
                    $json['warn'] = $warn;
                    break;
                }
            }

            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                delete(array('table' => self::table_detail, 'where' => " id not in ('" . implode("','", $detailIdIdArr) . "') and orderId = '$id'"));
                delete(array('table' => self::table_source, 'where' => " id not in ('" . implode("','", $mxIdArr) . "') and orderId = '$id'"));
                delete(array('table' => self::table_num, 'where' => "orderId = '$id'"));
                $this->commitTrans();
                $materialDis = new materialDistributeClass();
                //数量分配
                $bool = $materialDis->numDis($field['type'], $id);
                if ($bool !== true) {
                    $json['warn'] = $bool;
                    delete(array('table' => self::table_detail, 'where' => "orderId = '$id'"));
                    delete(array('table' => self::table_source, 'where' => "orderId = '$id'"));
                    delete(array('table' => self::table, 'where' => "id = '$id'"));
                } else {
                    if ($json['warn'] == '新增成功') {
                        auditingFollow(array(
                            "type" => "材料倒冲",
                            "typeId" => $id,
                            "text" => "【{$this->control['name']}】新增",
                            'job' => self::findStaffDepartment(self::$stid) . '-' . $this->controlJob['name'],
                            'staffName' => $this->control['name'],
                        ));
                    }
                    //添加日志
                    $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                    $text = $this->control['name'] . $type . "了" . self::title . " id：【" . $id . '】';
                    $this->logText(["type" => self::page, "text" => $text]);
                    //返回
                    $_SESSION['warn'] = $json['warn'];
                    $json['warn'] = 2;
                    $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $id;
                }

            } else {
                $this->rollback();
            }
        }

        resp:
        return json_encode($json, 320);
    }


    /*详情页*/
    public function detail(): string
    {
        $info = query(self::table, " id = '{$this->get('id')}'");
        if (empty($info['id'])) {
            $html = '未找到此' . self::title;
        } else {
            //菜单
            $data = array(
                "id" => $info['id'],
            );
            $button = [];
            $materialDis = new materialDistributeClass();
            $costAllocation = new costAllocationClass();
            $machiningOrderObj = new machiningOrderClass();
            if ($this->power(self::page, "confirm") && $info['state'] == '待确认') {
                $button[] = [
                    "name" => "确认",
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "operate",
                    "post" => ["act" => 'confirm', "id" => $info['id']],
                    'style' => 'li-btn-blue-bg',
                ];
            }
            if ($info['state'] != '已确认') {
                if ($this->power(self::page, "edit")) {
                    if ($info['state'] == '草稿') {
                        //按钮
                        $button[] = [
                            "name" => "提交",
                            "type" => "弹出层",
                            "cla" => $this->get('cla'),
                            "fun" => "operate",
                            "post" => ["act" => 'commit', "id" => $info['id']],
                            'style' => 'li-btn-blue-bg',
                        ];
                    }
                    //按钮
                    $button[] = [
                        "name" => "编辑",
                        "type" => "顶部页卡",
                        "title" => "编辑用户",
                        "url" => $this->root . "control/adIndex.html?cla={$this->get('cla')}&fun=edit&id=" . $info['id'],

                    ];
                }
                if ($this->power(self::page, "del")) {
                    //按钮
                    $button[] = [
                        "name" => "删除",
                        "type" => "弹出层",
                        "cla" => $this->get('cla'),
                        "fun" => "operate",
                        "post" => ["act" => 'del', "id" => $info['id']],
                    ];
                }
            }
            if ($this->power(self::page, "cancel") && $info['state'] == '已确认') {
                $button[] = [
                    "name" => "撤回",
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "operate",
                    "post" => ["act" => 'cancel', "id" => $info['id']],
                ];
            }
            //操作记录
            $button[] = self::operateLogBut($info['id']);

            $line = query('product_line',"id = '$info[lineId]'");
            $disHtml = '';
            unset($sourceTr);
            $sourceTr[] = ['单据日期', '单据编号', '加工类型', '生产线', '存货类别', '物料编码', '物料名称', '规格型号', '单位', '计划数量', '合格数量', '报废数量', 'BOM版本'];
            $result = find(array('table' => self::table_source, 'where' => "orderId = '$info[id]' order by list"));
            foreach ($result['array'] as $array){
                $machining_order_mx = query('machining_order_mx', "id = '$array[machiningOrderMxId]'");
                $machining_order = query('machining_order', "id = '$machining_order_mx[orderId]'");
                $type = $machining_order['orderType'] == '生产计划' ? '生产计划单' : '半成品加工单';
                $material = query('material', "id = '$machining_order_mx[materialId]'");
                $bom = query('bom', "id = '$machining_order_mx[bomId]'");
                $passNum = $costAllocation->getMaterialNum($machining_order_mx['id'], $machining_order_mx['unit']);
                $scrapNum = $costAllocation->getMaterialNum($machining_order_mx['id'], $machining_order_mx['unit'], '报废');
                unset($tempTrOne);
                $tempTrOne[] = [
                    $machining_order['recordDate'],
                    $machining_order['orderNo'],
                    $type,
                    $line['workshop'] . '-' . $line['name'],
                    $material['subject'],
                    $material['code'],
                    $material['name'],
                    $material['model'],
                    $machining_order_mx['unit'],
                    self::lostZero($machining_order_mx['num'],'numPrecision'),
                    $passNum,
                    $scrapNum,
                    $bom['bomVersion']
                ];
                $tempTrOne = array_merge($sourceTr,$tempTrOne);
                $tempHtml="<div class='single_material'><div class='div-title'>生产产品</div>".$this->tableMany(array('tr' => $tempTrOne, 'showSort' => true));
                //配料明细
                $tempHtml.="<div class='div-title'>配料明细</div>";
                //领料明细
                unset($deliveryTr);
                $deliveryTr[] = ['存货类别','物料编码', '物料名称', '规格型号', '单位','实际BOM用量','实际分配用量'];
                $deliveryAll = find(array(
                    'table'=>self::table_num,
                    'where'=>"machiningOrderMxId = '$array[machiningOrderMxId]' and sourceId = '$array[id]' and num >0 order by list"
                ));
                $bomArray = $machiningOrderObj->getFactMaterialNum($machining_order['id']);
                $totalArr = ['bom'=>0,'num'=>0];
                foreach ($deliveryAll['array'] as $deliveryInfo){
                    $material = query('material', "id = '$deliveryInfo[materialId]'");
                    $bom = $machiningOrderObj->getMaterialBom($bomArray,$array['machiningOrderMxId'],$material['id']);
                    $deliveryTr[] = [
                        $material['subject'],
                        $material['code'],
                        $material['name'],
                        $material['model'],
                        $deliveryInfo['unit'],
                        $bom,
                        self::lostZero($deliveryInfo['num'],'numPrecision')
                    ];
                    $totalArr['bom'] += $bom;
                    $totalArr['num'] += $deliveryInfo['num'];
                }
                $total_tr = [
                    5  => self::lostZero($totalArr['bom'],'num'),
                    6  => self::lostZero($totalArr['num'],'num'),
                ];
                $tempHtml.=$this->listTable(array('tr'=>$deliveryTr, 'showSort' => true, 'total' => $total_tr));
                $disHtml.=$tempHtml."</div>";
            }

            //生成表单
            $data['button'] = $this->tableShowButton($button);
            $data['html'] = $this->tableShow(array(
                "基本信息" => array(
                    array(
                        "生产线" => $line['workshop'] . '-' . $line['name'],
                        "分配方式"=>$materialDis->typeOption[$info['type']],
                        "单据日期" => $info['recordDate'],
                        '制单时间'=>$info['time'],
                    ),
                    array(
                        "制单人" => self::findStaff($info['stid']),
                        "状态" => $info['state']
                    ),
                ),

            ));
            $data['html'] .= $this->detailList([
                'title' => '材料分配明细',
                'html' => $disHtml,
            ]);
            //生成页面
            $data['html'].=$this->css();
            $html = $this->tab($data);
        }
        //返回
        return $html;
    }

    private function css(): string
    {
        return <<<eof
<style>
.div-title{width: 100%;padding: 5px}
.single_material{padding: 10px;margin: 0 0 20px 0;border: 1px dashed #e6e6e6;}
</style>
eof;

    }

    /**
     * 确认
     */
    public function confirmEdit(): bool|string
    {
        $id = $this->post('id');
        $info = query(self::table, " id = '$id'");
        $field = [
            'state' => '已确认',
            'checkId' => self::$stid,
            'confirmTime' => $this->time
        ];
        //判断当前线边库存是否足够
        $warn='';
        $all = find(array('table' => 'material_distribute_num', 'where' => "orderId = '$info[id]' order by list"));
        $zeroOutCtrl = optionSettingClass::getSettingItem('库存','zeroOutCtrl');
        if($zeroOutCtrl) {  //倒冲时进行零出库控制
            foreach ($all['array'] as $array) {
                $stockNum = tempInventoryClass::inventoryNum($array['materialId'], $array['unit'], $info['lineId']);
                if ($stockNum < $array['num']) {
                    $line = query('product_line', "id = '$info[lineId]'");
                    $warn = "线边库存生产线【{$line['workshop']}-{$line['name']}】物料【" . materialClass::getName($array['materialId']) . "】数量不足";
                    break;
                }
            }
        }
        if (!$this->power(self::page, 'confirm')) {
            $json['warn'] = '你还没有确认权限';
        } elseif (empty($info['id'])) {
            $json['warn'] = '未找到此材料分配记录';
        }  elseif ($info['state'] != '待确认') {
            $json['warn'] = '此材料分配记录不是待确认状态，不能确认';
        } elseif($warn){
            $json['warn'] = $warn;
        }else {
            $this->startTrans();
            $json['warn'] = update(array(
                "table" => self::table,
                "field" => $field,
                "where" => "id = '$info[id]'",
            ));
            //生成线边库存出库记录
            foreach ($all['array'] as $array){
                $bool = tempInventoryClass::insertRecord(array(
                    'lineId' => $info['lineId'],
                    'materialId' => $array['materialId'],
                    'num' => -$array['num'],
                ));
                if ($bool !==true){
                    $json['warn'] = $bool;
                    break;
                }
            }

            if (in_array($json['warn'], ["更新成功"])) {
                $this->commitTrans();
                auditClass::operateRecord($id,self::title,'确认');
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . "id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
            } else {
                $this->rollback();
            }
        }
        resp:
        return json_encode($json, 320);
    }
    /**
     * 撤回
     */
    public function cancelEdit()
    {
        $id = $this->post('id');
        $info = query(self::table, " id = '$id'");
        $field = [
            'state' => '草稿',
            'checkId' => '',
            'confirmTime' => ''
        ];
        if (!$this->power(self::page, 'cancel')) {
            $json['warn'] = '你还没有撤回权限';
        } elseif (empty($info['id'])) {
            $json['warn'] = '未找到此'.self::title;
        } elseif ($info['state'] != '已确认') {
            $json['warn'] = '此发'.self::title.'不是已确认状态，无需撤回';
        }  else {
            $this->startTrans();

            $json['warn'] = update(array(
                "table" => self::table,
                "field" => $field,
                "where" => "id = '$info[id]'",
            ));
            $all = find(array('table'=>'material_distribute_num','where'=>"orderId = '$info[id]' order by list"));
            //生成线边库存出库记录
            foreach ($all['array'] as $array){
                $bool = tempInventoryClass::insertRecord(array(
                    'lineId' => $info['lineId'],
                    'materialId' => $array['materialId'],
                    'num' => $array['num'],
                ));
                if ($bool !==true){
                    $json['warn'] = $bool;
                    break;
                }
            }
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                auditClass::operateRecord($id,self::title,'撤回');
                $this->commitTrans();
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . "id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
            }else{
                $this->rollback();
            }
        }
        resp:
        return json_encode($json, 320);
    }

    /**
     * 提交
     */
    public function commitEdit(): bool|string
    {
        $id = $this->post('id');
        $info = query(self::table, " id = '$id'");
        $field = [
            'state' => '待确认',
        ];
        //判断当前线边库存是否足够
        $warn='';
        $zeroOutCtrl = optionSettingClass::getSettingItem('库存','zeroOutCtrl');
        if($zeroOutCtrl) {  //倒冲时进行零出库控制
            $all = find(array('table' => 'material_distribute_num', 'where' => "orderId = '$info[id]' order by list"));
            foreach ($all['array'] as $array) {
                $stockNum = tempInventoryClass::inventoryNum($array['materialId'], $array['unit'], $info['lineId']);
                if ($stockNum < $array['num']) {
                    $line = query('product_line', "id = '$info[lineId]'");
                    $warn = "线边库存生产线【{$line['workshop']}-{$line['name']}】物料【" . materialClass::getName($array['materialId']) . "】数量不足";
                    break;
                }
            }
        }
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = '你还没有编辑权限';
        } elseif (empty($info['id'])) {
            $json['warn'] = '未找到此材料分配记录';
        } elseif ($info['state'] != '草稿') {
            $json['warn'] = '此材料分配记录不是草稿状态，不能提交';
        }elseif($warn){
            $json['warn'] = $warn;
        } else {
            $this->startTrans();
            $json['warn'] = update(array(
                "table" => self::table,
                "field" => $field,
                "where" => "id = '$info[id]'",
            ));

            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                $this->commitTrans();
                auditingFollow(array(
                    "type" => "材料分配记录",
                    "typeId" => $info['id'],
                    "text" => "【{$this->control['name']}】提交",
                    'job' => self::findStaffDepartment(self::$stid) . '-' . $this->controlJob['name'],
                    'staffName' => $this->control['name'],
                ));
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . "id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
//                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
            }else{
                $this->rollback();
            }
        }
        resp:
        return json_encode($json, 320);
    }

    // 操作中转
    public function operate()
    {
        $act = $this->post('act') ?? '';
        $pwd = $word = false; // 需要密码
        $form = $power = '';
        switch ($act) {
            case 'cancel':
                $act = 'cancel';
                $msg = '撤回';
                $title = '是否确认撤回此' . self::title . '？';
                $function = 'cancelEdit';
                $form = self::page . 'OperateForm, detailForm';
                $power = '';
                $word = true;
                break;
            case 'confirm':
                $act = 'confirm';
                $msg = '确认';
                $title = '是否已确认此材料分配记录，确认后将不可修改？';
                $function = 'confirmEdit';
                $form = self::page . 'OperateForm, detailForm';
                $power = '';
                $word = true;
                break;
            case 'commit':
                $act = 'edit';
                $msg = '编辑';
                $title = '是否确认提交此材料分配记录？';
                $function = 'commitEdit';
                $form = self::page . 'OperateForm, detailForm';
                $power = '';
                $word = true;
                break;
            default:
                $act = 'del';
                $msg = '删除' . self::title;
                $title = self::page . 'Delete';
                $function = 'delete';
                $form = self::page . 'OperateForm, listForm, quoForm';
                $power = '';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = '你还没有' . $msg . '的权限';
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title' => $title,
                'function' => $function,
                'form' => $form,
                'power' => $power,
                'pwd' => $pwd,
                'word' => $word
            ]);
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 删除
     * @return bool|string
     */
    public function delete()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = "你没有删除的权限";
        } elseif (empty($array)) {
            $json['warn'] = "你一个数据都没有选择呢";
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " id = '$id' ");
                if ($info['state'] == '已确认') {
                    $warn = "删除失败：已确认，暂不能删除";
                } else {
                    //最后删除基本参数
                    delete(array("table" => self::table, "where" => " id = '$id' "));
                    delete(array("table" => self::table_num, "where" => " orderId = '$id' "));
                    delete(array("table" => self::table_source, "where" => " orderId = '$id' "));
                    delete(array("table" => self::table_detail, "where" => " orderId = '$id' "));
                    delete(array("table" => "auditing_follow", "where" => " typeId = '$id' "));
                    //返回
                    $warn = "删除成功";
                    $x++;
                }
                $text .= self::title . "ID【" . $info['id'] . "】" . $warn . "。<br>";
            }
            //添加日志
            $text = $this->control['name'] . "删除了" . self::title . "，结果如下：<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = "删除了" . $x . "个" . self::title . "，详情见系统日志。";
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }

}

